<script>
jQuery(document).ready(function() {

  /*
   **********************************
   * WORKING WITH JQUERY & ATTRIBUTES
   **********************************
   */

  // call to create a jquery/html attribute foreach real/existent attribute in Entity
  {foreach from=$entity->attribute item="attribute"}
  addAtrribute({$attribute->id});
  {/foreach}

  // we make a vertical tabs list and their panels
  jQuery(".attributes-tab").on("click", "li", function() {
    event.preventDefault();

    jQuery(".attributes-tab li").removeClass("active");
    jQuery(this).addClass("active");

    var verticalTabID = jQuery(this).children("a").attr("href");
    jQuery("#attributes .tab-pane").hide();
    jQuery(verticalTabID).show();
  });

  // catch onClick event for create new attributes
  jQuery("#create_attribute").on("click", function() {
    event.preventDefault();
    addAtrribute(0);
  });

  // remove attributes
  jQuery("#attributes").on("click", ".tab-content .remove-attribute", function() {
    event.preventDefault();
    jQuery(".attributes-tab li").removeClass("active");
    jQuery("#attributes .tab-pane").hide();

    var liID = jQuery(this).parent().attr("id");

    //  tab-pane and remove li
    jQuery(this).parent().remove();
    jQuery('#attributes a[href=#'+liID+']').parent().remove();

    // // activate first tab
    var $firstTab = jQuery(".attributes-tab li:eq(0)");
    $firstTab.addClass("active");
    jQuery($firstTab.children("a").attr("href")).show();
  });

  // making attributes
  // this function call an ajax to receive a "ready for use" html attribute
  // if attribute_id exists, ajax return an existent attribute
  // else, ajax will return a new html attribute
  function addAtrribute(attribute_id) {
    jQuery.post("attributes/get_attribute/"+attribute_id+"/",
      function(data) {
        var navTabs = jQuery(".attributes-tab ul.nav-tabs").append('<li><a href="#" data-toggle="tab"></a></li>');
        var tabContent = jQuery(".attributes-tab .tab-content").append(data);
        var newPane = tabContent.find(".tab-pane").last();

        var lastTab = navTabs.children().last();

        lastTab.find("a").html(newPane.find("#attr_name").val());
        lastTab.find("a").attr("href","#"+newPane.attr("id"));
        lastTab.find("a").tab("show");

        // will catch onChange event for input name
        // if pane name change, this will to change the tab name
        newPane.find("#attr_name").change(function() {
          lastTab.find("a").html(jQuery(this).val());
        });

        // will catch onKeyUp event for input name
        // if pane name change, this will to change the tab name
        newPane.find("#attr_name").keyup( function() {
          lastTab.find("a").html(jQuery(this).val());
        });
      }
    );
  }

}); // ready
</script>
